package com.weilele.leisure.time.ui.module.video_detail


import android.os.Bundle
import androidx.fragment.app.Fragment
import com.weilele.base.library.BaseBindingFragment
import com.weilele.leisure.time.bean.VideoDetailBean
import com.weilele.leisure.time.databinding.FragmentPlayListBinding
import com.weilele.leisure.time.ui.dialog.CacheListDialog
import com.weilele.leisure.time.ui.holder.PlayListItemHolder
import com.weilele.mvvm.adapter.refreshList
import com.weilele.mvvm.base.helper.annotation.MvvmActivityViewModel
import com.weilele.mvvm.base.helper.createViewModel
import com.weilele.mvvm.base.livedata.LiveDataWrap
import com.weilele.mvvm.base.livedata.data
import com.weilele.mvvm.base.livedata.wrapSuccessObserver
import com.weilele.mvvm.utils.activity.onClick
import com.weilele.mvvm.utils.formJsonString
import com.weilele.mvvm.utils.fragment.arguments
import com.weilele.mvvm.utils.toJsonString

class PlayListFragment : BaseBindingFragment<FragmentPlayListBinding>() {
    companion object {
        private const val KEY_VIDEO_LIST = "KEY_VIDEO_LIST"
        fun newInstance(position: Int): Fragment {
            return PlayListFragment().apply {
                arguments {
                    putInt(KEY_VIDEO_LIST, position)
                }
            }
        }
    }

    private val videoDetailViewModel: VideoDetailViewModel by lazy {
        requireParentFragment().createViewModel()
    }

    private val playersDTO by lazy {
        videoDetailViewModel.videoDetailData.data?.players?.get(currentPageIndex)
    }
    private val currentPageIndex by lazy {
        arguments?.getInt(KEY_VIDEO_LIST) ?: 0
    }


    private val adapter by lazy {
        PlayListItemHolder.newInstance().apply {
            setOnHolderClickListener { holder, clickView ->
                videoDetailViewModel.startPlay(
                    videoDetailViewModel.videoDetailData.data,
                    playersDTO,
                    this.currentList.toMutableList(), holder.bindingPosition
                )
            }
        }
    }


    override fun initUi(savedInstanceState: Bundle?) {
        super.initUi(savedInstanceState)
        mBinding.playListRcv.adapter = adapter
        adapter.refreshList(playersDTO?.datas)
    }

    override fun getObserverLiveData(): List<LiveDataWrap>? {
        return listOf(
            videoDetailViewModel.playListChangeData wrapSuccessObserver ::onPlayChange
        )
    }

    private fun onPlayChange(pair: Pair<String?, Int>) {
        adapter.currentList.forEachIndexed { index, datasDTO ->
            val newValue = pair.first == playersDTO?.key && pair.second == index
            if (datasDTO.isSelect != newValue) {
                datasDTO.isSelect = newValue
                adapter.notifyItemChanged(index)
            }
        }
    }
}